<template>
  <div class="userLoginPage">
    <h2 class="userLoginPage-title">鸡哥AI应用生成-用户注册</h2>
    <h3 class="userLoginPage-desc">不写一行代码，生成完整应用</h3>
    <a-form :model="formState" autocomplete="off" name="normal_login" @finish="handleSubmit">
      <a-form-item
        :rules="[{ required: true, message: '请输入账号' }]"
        label="用户名"
        name="userAccount"
      >
        <a-input v-model:value="formState.userAccount" placeholder="请输入用户名">
          <template #prefix>
            <UserOutlined class="site-form-item-icon" />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 8, message: '密码长度不能小于8' },
        ]"
        label="密码"
        name="userPassword"
      >
        <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码">
          <template #prefix>
            <LockOutlined class="site-form-item-icon" />
          </template>
        </a-input-password>
      </a-form-item>

      <div class="tips">
        没有账号？
        <RouterLink to="/user/register">去注册</RouterLink>
      </div>

      <a-form-item>
        <a-button class="login-form-button" html-type="submit" style="width: 100%" type="primary">
          登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
import { LockOutlined, UserOutlined } from '@ant-design/icons-vue'
import { userLogin } from '@/api/userController.ts'
import { useLoginUserStore } from '@/stores/loginUser.ts'
import { message } from 'ant-design-vue'
import router from '@/router'

interface FormState {
  userAccount: string
  userPassword: string
}

const formState = reactive<API.UserLoginRequest>({
  userAccount: '',
  userPassword: '',
})

const loginUserStore = useLoginUserStore()

//  用户登录
const handleSubmit = async (values: any) => {
  const res = await userLogin(values)
  // 登录成功，把登录态保存到全局状态中
  if (res.data.code === 0 && res.data.data) {
    await loginUserStore.fetchLoginUser()
    message.success('登录成功')
    await router.push({
      path: '/',
      replace: true,
    })
  } else {
    message.error('登录失败' + res.data.message)
  }
}
</script>
<style scoped>
.userLoginPage {
  width: 360px;
  margin: 300px auto;
  height: 600px;
}

.tips {
  text-align: right;
  margin-bottom: 16px;
}

.userLoginPage-title {
  text-align: center;
}

.userLoginPage-desc {
  text-align: center;
  font-weight: lighter;
  margin-bottom: 32px;
}
</style>
